import { Color } from 'https://unpkg.com/three/build/three.module.js';
import { initShaders } from '../jsm/Utils.js';
import lib from '../jsm/ThreeLib.js';

window.onload = function () {

    const backColor = new Color("rgba(0,0,0,1)");

    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext("webgl");
    //开启颜色合成,才会有透明度的感觉
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    //初始化着色器
    initShaders(gl,
        document.querySelector("#vertexShader").innerText,
        document.querySelector("#fragmentShader").innerText);


    let vertices = [];
    //缓冲对象 
    var vertexBuffer = gl.createBuffer();
    //绑定缓冲对象
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    //写入数据(缓冲区对象,顶点数据,写入方式[一次性写入])
    // gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);


    var a_posi = gl.getAttribLocation(gl.program, 'a_Position');
    gl.vertexAttribPointer(a_posi, 2, gl.FLOAT, false, 0, 0);

    var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
    gl.vertexAttrib1f(a_PointSize, 20);

    var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    gl.uniform4fv(u_FragColor, [1, 1, 0, 1]);

    //赋能-批处理
    gl.enableVertexAttribArray(a_posi);

    lib.clearCanvas(gl, backColor, 1);


    gl.drawArrays(gl.POINTS, 0, vertices.length / 2);
    canvas.addEventListener("click", function (event) {
        const { clientX, clientY } = event;
        const { left, top, width, height } = canvas.getBoundingClientRect();
        const [cssX, cssY] = [clientX - left, clientY - top];

        var [x, y] = [lib.GetPosiOfX(width, cssX), lib.GetPosiOfY(height, cssY)];

        vertices.push(x, y);
        //每次进行写入,且不会清空
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

        lib.clearCanvas(gl, backColor, 1);
        gl.drawArrays(gl.POINTS, 0, vertices.length / 2);
        if (vertices.length / 2 >= 3) {
            gl.drawArrays(gl.TRIANGLE_FAN, 0, vertices.length / 2);
        }
    })

    //填充三角形
    // gl.drawArrays(gl.TRIANGLES, 0, 6);
    //三角带
    //第一个三角形 0-1-2
    //第偶数个三角形:以上一个三角形的第二条边与下一个点为基础,以和第二条边相反的方向绘制三角形
    //第偶数个三角形:以上一个三角形的第三条边与下一个点为基础,以和第二条边相反的方向绘制三角形
    // gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertices.length);
    //三角扇
    //下一个三角形:以上一个三角形的第三条边与下一个点为基础,以和第三条边相反的方向绘制三角形
    // gl.drawArrays(gl.TRIANGLE_FAN, 0, vertices.length);
    //可视的点
    // gl.drawArrays(gl.POINTS, 0, vertices.length);
    //两个点组成的线段
    // gl.drawArrays(gl.LINES, 0, 4);
    //连续的线条
    // gl.drawArrays(gl.LINE_STRIP, 0, 4);
    //收尾闭合的线条
    // gl.drawArrays(gl.LINE_LOOP, 0, 4);





}